import traceback

import openpyxl

from app.commons.config import async_exec
from .functions import *
import time


@async_exec
def match_result(filename):
    files_path = "files/"
    start = time.perf_counter()
    config = load_config(get_datetime_from_file(filename))
    print(config)
    CurrentStockFileName = files_path + merge_filename("stock/CurrentStock.xlsx", get_datetime_from_file(filename))
    DownloadStockFile(get_datetime_from_file(filename))  # filename:  file_20211111235959.xlsx
    CurrentStockSheetName = "Sheet1"
    RequirementFileName = files_path + filename
    RequirementSheetName = "Sheet1"
    CacheFileName = files_path + "cache.json"
    CacheExpireTime = 7200
    LogFileName = files_path + merge_filename("log/log.txt", get_datetime_from_file(filename))
    ExportFileName = files_path + merge_filename("result/result.xlsx", get_datetime_from_file(filename))
    CurrentStockMap = config["CurrentStockMap"]
    RequirementMap = config["RequirementMap"]
    CurrentStockAllHeaders = GetAllHeadersForExcel(CurrentStockFileName, CurrentStockSheetName)
    RequirementAllHeaders = GetAllHeadersForExcel(RequirementFileName, RequirementSheetName)
    CurrentStockNeedHeaders = LoadNeedHeaders(CurrentStockMap)
    RequirementNeedHeaders = LoadNeedHeaders(RequirementMap)
    if CheckIfhaveAllNeed(CurrentStockNeedHeaders, CurrentStockAllHeaders) and CheckIfhaveAllNeed(
            RequirementNeedHeaders, RequirementAllHeaders):
        print('loading excel1...')
        CurrentStockExcelByPanda = pd.read_excel(CurrentStockFileName, CurrentStockSheetName,
                                                 usecols=getNeedColumns(CurrentStockAllHeaders,
                                                                        CurrentStockNeedHeaders),
                                                 converters={CurrentStockMap["order_id"]: str,
                                                             CurrentStockMap["unique_code"]: str})
        print('Success!')
        print('loading excel2...')
        RequirementExcelByPanda = pd.read_excel(RequirementFileName, RequirementSheetName,
                                                usecols=getNeedColumns(RequirementAllHeaders, RequirementNeedHeaders),
                                                converters={RequirementMap["order_id"]: str,
                                                            CurrentStockMap["unique_code"]: str})
        RequirementFileByWorkBook = openpyxl.load_workbook(RequirementFileName)
        print('Success!')
        RequirementFileWorkSheet = RequirementFileByWorkBook[RequirementSheetName]
        CurrentStockData, UniqueCodeList = FetchUniqueCodeFromCurrentStock(CurrentStockExcelByPanda, CacheFileName,
                                                                           CurrentStockMap, CacheExpireTime)
        FillDataIntoRequirementFile(RequirementFileWorkSheet,
                                    CurrentStockData,
                                    RequirementExcelByPanda, RequirementAllHeaders, RequirementMap, LogFileName)
        ExportWorkBook = openpyxl.Workbook()
        GenerateExportFile(RequirementFileByWorkBook, ExportWorkBook,
                           RequirementAllHeaders, RequirementMap, UniqueCodeList, config)
        print('Wrting into %s...' % (ExportFileName))
        ExportWorkBook.save(ExportFileName)
        print('Success!')
    else:
        with open(LogFileName, "w+") as f3:
            print("Don't have enough colmuns!")
            f3.writelines("Don\'t have enough colmuns!")
    end = time.perf_counter()
    print("Running Time: %s seconds." % (end - start))


if __name__ == '__main__':
    match_result()
